package com.xygj.vueblog.utils;

import io.jsonwebtoken.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import sun.rmi.runtime.Log;

import java.nio.channels.Pipe;
import java.util.Date;

@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "xyzq.jwt")
public class JwtUtils {

    private String secret;
    private long expire;
    private String header;

    /**
     * 生成jwt token
     * @return
     */
    public String generatorToken(long userId){

        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);
        return Jwts.builder()
                .setHeaderParam("tye","JWT")
                .setSubject(userId+"")
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();

    }

    public Claims getClaimByToken(String token){

        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            return null;
        }
    }

    /**
     * token是否过期
     *
     * return true 过期
     * @param expiration
     * @return
     */
    public boolean isTokenExpired(Date expiration){

        return expiration.before(new Date());
    }
}
